package cn.gavin.service.impl;

import cn.gavin.domain.Department;
import cn.gavin.domain.Employee;
import cn.gavin.domain.Permission;
import cn.gavin.mapper.PermissionMapper;
import cn.gavin.qo.QueryObject;
import cn.gavin.service.IPermissionService;
import cn.gavin.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void deleteById(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public Permission findById(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> permissions = permissionMapper.dataList(qo);
        return new PageInfo<>(permissions);
    }

    @Autowired
    private ApplicationContext ac;

    @Override
    public void reload() {
        List<String> expressions = permissionMapper.selectAllExpression();
        Map<String, Object> map = ac.getBeansWithAnnotation(Controller.class);
        Collection<Object> values = map.values();
        for (Object value : values) {
            Class<?> aClass = value.getClass();
            Method[] methods = aClass.getDeclaredMethods();
            for (Method method : methods) {
                RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                if (annotation != null){
                    String expression = annotation.expression();
                    String name = annotation.name();
                    if (expressions.contains(expression)){
                        continue;
                    }
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setExpression(expression);
                    permissionMapper.insert(permission);
                    expressions.add(expression);
                }
            }
        }
    }

    @Override
    public List<String> selectByEmpId(Long id) {
        return permissionMapper.selectByEmpId(id);
    }
}
